package com.googlecode.rotools.grf;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import com.googlecode.rotools.rocommon.IOUtil;

public class GrfTool {
	private static final String PREFIX = "grfdata";
	private static final String SUFFIX = ".tmp";
	private static final String DIRRECTORY = ".";
	private static final String COMMAND = "grf";
	
	private HashMap<Class<?>, TextParser<?>> paeserMap = new HashMap<Class<?>, TextParser<?>>();
	private File file;
	private IOUtil ioUtil = new IOUtil();
	
	public GrfTool(File grfFile) {
		super();
		this.file = grfFile;
		paeserMap.put(CardPrefixName.class, new CardPrefixNameParser());
		paeserMap.put(ItemDesc.class, new ItemDescParser());
		paeserMap.put(ItemDisplayName.class, new ItemDisplayNameParser());
		paeserMap.put(ItemParam.class, new ItemParamParser());
		paeserMap.put(ItemSlotCount.class, new ItemSlotCountParser());
		paeserMap.put(ItemSlot.class, new ItemSlotParser());
		
	}
	public byte[] extract(String name) throws IOException, InterruptedException{
		File file = File.createTempFile(PREFIX, SUFFIX, new File(DIRRECTORY));
		try{
			file.deleteOnExit();
			extract(name, file);
			return ioUtil.readBytes(file);
			
		}finally{
			file.delete();
			
		}
	}
	public void extract(String name, File destination) throws IOException, InterruptedException{
		Process process = Runtime.getRuntime().exec(new String[]{COMMAND, file.getAbsolutePath(), name, destination.getAbsolutePath()});
		process.waitFor();
		
	}
	@SuppressWarnings("unchecked")
	public <T> List<T> extract(Class<T> clazz, String name) throws Exception {
    	TextParser<?> parser = paeserMap.get(clazz);
		return (List<T>)parser.parse(extract(name));

    }
}
